<template>
  <div class="dashboard">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">数据概览</h1>
      <p class="page-subtitle">欢迎回来，{{ authStore.user?.realName || authStore.user?.username }}</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <el-card class="stat-card" shadow="never">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-number">{{ stats.totalBooks || 0 }}</div>
            <div class="stat-label">图书总数</div>
            <div class="stat-desc">系统中的所有图书</div>
          </div>
          <div class="stat-icon books">
            <el-icon><Reading /></el-icon>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="never">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-number">{{ stats.totalUsers || 0 }}</div>
            <div class="stat-label">注册用户</div>
            <div class="stat-desc">平台注册用户数量</div>
          </div>
          <div class="stat-icon users">
            <el-icon><User /></el-icon>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="never">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-number">{{ stats.activeBorrows || 0 }}</div>
            <div class="stat-label">借阅中</div>
            <div class="stat-desc">当前借阅中的图书</div>
          </div>
          <div class="stat-icon borrows">
            <el-icon><Files /></el-icon>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="never">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-number">{{ stats.overdueBooks || 0 }}</div>
            <div class="stat-label">逾期图书</div>
            <div class="stat-desc">需要及时归还的图书</div>
          </div>
          <div class="stat-icon overdue">
            <el-icon><Warning /></el-icon>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 内容区域 -->
    <div class="content-grid">
      <!-- 快捷操作 -->
      <el-card class="section-card" shadow="never">
        <template #header>
          <div class="card-header">
            <h3>快捷操作</h3>
          </div>
        </template>
        <div class="quick-actions">
          <div class="action-item" @click="$router.push('/books')">
            <div class="action-icon">
              <el-icon><Search /></el-icon>
            </div>
            <div class="action-info">
              <div class="action-title">浏览图书</div>
              <div class="action-desc">查看和搜索图书信息</div>
            </div>
            <el-icon class="action-arrow"><ArrowRight /></el-icon>
          </div>

          <div class="action-item" @click="$router.push('/borrows')">
            <div class="action-icon">
              <el-icon><Files /></el-icon>
            </div>
            <div class="action-info">
              <div class="action-title">我的借阅</div>
              <div class="action-desc">管理您的借阅记录</div>
            </div>
            <el-icon class="action-arrow"><ArrowRight /></el-icon>
          </div>

          <div v-if="authStore.isAdmin" class="action-item" @click="$router.push('/admin/books')">
            <div class="action-icon">
              <el-icon><Setting /></el-icon>
            </div>
            <div class="action-info">
              <div class="action-title">系统管理</div>
              <div class="action-desc">管理图书和用户信息</div>
            </div>
            <el-icon class="action-arrow"><ArrowRight /></el-icon>
          </div>
        </div>
      </el-card>

      <!-- 最近借阅 -->
      <el-card class="section-card" shadow="never">
        <template #header>
          <div class="card-header">
            <h3>最近借阅</h3>
            <el-button type="text" @click="$router.push('/borrows')">查看全部</el-button>
          </div>
        </template>
        <div class="recent-borrows">
          <div v-if="recentBorrows.length === 0" class="empty-state">
            <el-icon><Reading /></el-icon>
            <p>暂无借阅记录</p>
            <el-button type="primary" @click="$router.push('/books')">开始借阅</el-button>
          </div>
          
          <div v-else class="borrow-list">
            <div 
              v-for="borrow in recentBorrows" 
              :key="borrow.id"
              class="borrow-item"
            >
              <div class="book-cover">
                <el-icon><Reading /></el-icon>
              </div>
              <div class="book-info">
                <div class="book-title">{{ (borrow.book && (borrow.book.name || borrow.book.title)) || '未知图书' }}</div>
                <div class="book-meta">
                  <span>作者：{{ (borrow.book && borrow.book.author) || '未知' }}</span>
                  <span>借阅日期：{{ formatDate(borrow.borrowDate) }}</span>
                </div>
              </div>
              <div class="borrow-status">
                <el-tag 
                  :type="getBorrowStatusType(borrow.status)" 
                  size="small"
                >
                  {{ getBorrowStatusText(borrow.status) }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 通知公告 -->
    <el-card class="section-card announcement-card" shadow="never">
      <template #header>
        <div class="card-header">
          <h3>通知公告</h3>
        </div>
      </template>
      <div class="announcement-content">
        <div class="announcement-item">
          <el-icon class="announcement-icon"><Bell /></el-icon>
          <div class="announcement-text">
            <div class="announcement-title">系统维护通知</div>
            <div class="announcement-desc">系统将于本周六 02:00-04:00 进行例行维护，期间服务可能短暂中断。</div>
            <div class="announcement-time">2024-06-15 发布</div>
          </div>
        </div>
        
        <div class="announcement-item">
          <el-icon class="announcement-icon"><Bell /></el-icon>
          <div class="announcement-text">
            <div class="announcement-title">借阅规则更新</div>
            <div class="announcement-desc">图书借阅期限调整为30天，请各位读者注意按时归还。</div>
            <div class="announcement-time">2024-06-10 发布</div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import request from '@/utils/request'

const authStore = useAuthStore()

const stats = ref({
  totalBooks: 0,
  totalUsers: 0,
  activeBorrows: 0,
  overdueBooks: 0
})

const recentBorrows = ref([])

// 获取统计数据
const fetchStats = async () => {
  try {
    const response = await request.get('/statistics/overview')
    if (response.code === 200) {
      stats.value = {
        totalBooks: response.data.totalBooks || 0,
        totalUsers: response.data.totalUsers || 0,
        activeBorrows: response.data.activeBorrows || 0,
        overdueBooks: response.data.overdueBooks || 0
      }
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    // 失败时使用默认值
    stats.value = {
      totalBooks: 0,
      totalUsers: 0,
      activeBorrows: 0,
      overdueBooks: 0
    }
  }
}

// 获取最近借阅记录
const fetchRecentBorrows = async () => {
  try {
    const params = {
      current: 1,
      size: 3,
      userId: authStore.user && authStore.user.id
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await request.get('/borrows/page', { params })
    if (response.code === 200) {
      const data = response.data
      const borrowsData = data.records || []
      
      // 获取图书详细信息
      for (const borrow of borrowsData) {
        try {
          const bookResponse = await request.get(`/books/${borrow.bookId}`)
          if (bookResponse.code === 200) {
            borrow.book = bookResponse.data
          }
        } catch (error) {
          console.error('获取图书信息失败:', error)
          borrow.book = { name: '获取失败', author: '未知' }
        }
      }
      
      recentBorrows.value = borrowsData
    }
  } catch (error) {
    console.error('获取借阅记录失败:', error)
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取借阅状态类型
const getBorrowStatusType = (status) => {
  switch (status) {
    case 'BORROWED':
    case '0': return 'warning'  // 借阅中
    case 'RETURNED':
    case '1': return 'success'  // 已归还
    case 'OVERDUE':
    case '2': return 'danger'   // 已逾期
    default: return 'info'
  }
}

// 获取借阅状态文本
const getBorrowStatusText = (status) => {
  switch (status) {
    case 'BORROWED':
    case '0': return '借阅中'
    case 'RETURNED':
    case '1': return '已归还'
    case 'OVERDUE':
    case '2': return '已逾期'
    default: return '未知'
  }
}

onMounted(() => {
  fetchStats()
  fetchRecentBorrows()
})
</script>

<style scoped>
.dashboard {
  max-width: 1200px;
  margin: 0 auto;
}

/* 页面标题 */
.page-header {
  margin-bottom: 32px;
}

.page-title {
  font-size: 28px;
  color: #262626;
  margin-bottom: 8px;
  font-weight: 600;
}

.page-subtitle {
  font-size: 16px;
  color: #595959;
  margin: 0;
}

/* 统计卡片网格 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.stat-card {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  transition: box-shadow 0.2s;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #262626;
  line-height: 1.2;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 16px;
  color: #595959;
  font-weight: 500;
  margin-bottom: 2px;
}

.stat-desc {
  font-size: 14px;
  color: #8c8c8c;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  color: #ffffff;
}

.stat-icon.books {
  background-color: #1890ff;
}

.stat-icon.users {
  background-color: #52c41a;
}

.stat-icon.borrows {
  background-color: #faad14;
}

.stat-icon.overdue {
  background-color: #ff4d4f;
}

/* 内容网格 */
.content-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 32px;
}

.section-card {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #262626;
  font-weight: 600;
}

/* 快捷操作 */
.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.action-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.action-item:hover {
  background-color: #fafafa;
  border-color: #d9d9d9;
}

.action-icon {
  width: 40px;
  height: 40px;
  background-color: #f0f8ff;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: #1890ff;
  margin-right: 16px;
}

.action-info {
  flex: 1;
}

.action-title {
  font-size: 16px;
  color: #262626;
  font-weight: 500;
  margin-bottom: 4px;
}

.action-desc {
  font-size: 14px;
  color: #8c8c8c;
}

.action-arrow {
  font-size: 16px;
  color: #bfbfbf;
}

/* 最近借阅 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #8c8c8c;
}

.empty-state .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #d9d9d9;
}

.empty-state p {
  margin: 0 0 16px 0;
  font-size: 16px;
}

.borrow-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.borrow-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.book-cover {
  width: 48px;
  height: 48px;
  background-color: #f0f8ff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 20px;
  color: #1890ff;
}

.book-info {
  flex: 1;
}

.book-title {
  font-size: 16px;
  color: #262626;
  font-weight: 500;
  margin-bottom: 4px;
}

.book-meta {
  font-size: 14px;
  color: #8c8c8c;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.borrow-status {
  margin-left: 12px;
}

/* 通知公告 */
.announcement-card {
  grid-column: 1 / -1;
}

.announcement-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.announcement-item {
  display: flex;
  align-items: flex-start;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 6px;
}

.announcement-icon {
  font-size: 20px;
  color: #1890ff;
  margin-right: 12px;
  margin-top: 2px;
}

.announcement-text {
  flex: 1;
}

.announcement-title {
  font-size: 16px;
  color: #262626;
  font-weight: 500;
  margin-bottom: 4px;
}

.announcement-desc {
  font-size: 14px;
  color: #595959;
  line-height: 1.5;
  margin-bottom: 8px;
}

.announcement-time {
  font-size: 12px;
  color: #8c8c8c;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .content-grid {
    grid-template-columns: 1fr;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .stat-number {
    font-size: 28px;
  }
}
</style> 